class User < ActiveRecord::Base
  before_create { generate_token(:auth_token) }
  before_save :encrypt_password,:capitalize
  
  #Asociations--->
  has_many :posts
  
  #Validaciones---->
  validates_confirmation_of :password, :message => "no coincide"
  validates_presence_of :password,:rut,:email,:nickname, :on => :create, :message => "no puede estar en blanco"
  validates_uniqueness_of :email,:nickname, :rut, :message => "ya existe" , :scope => :deleted, :case_sensitive => false
  validates_format_of :nickname, :with => /^[A-Za-z\d_]+$/, :message=> "tiene caracteres invalidos",:on => :update
  validates :email, :email_format => true
  validates :rut, :rut_format => true 
  #validates_format_of :rut,:with => /\A(\d{1,3})\.(\d{1,3})\.(\d{1,3})\-(k|\d{1})\Z/i,:message => "formato rut incorrecto"
                        
  
  attr_accessible :email, :password, :password_confirmation, :name, :last_name, :nickname,:priority, :rut,:born,:login,:role,:confirmation,:faild_attempt,:deleted,:locked
  attr_accessor :password,:login,:accessible  

  #Metodos----->
  def send_password_reset
    generate_token(:password_reset_token)
    self.password_reset_sent_at = Time.zone.now
    save!
    UserMailer.password_reset(self).deliver
  end
  
  def send_email_confirmation
    generate_token(:auth_token)
    save!
    UserMailer.email_confirmation(self).deliver
  end

  def generate_token(column)
    begin
      self[column] = SecureRandom.base64.tr("+/", "-_")
    end while User.exists?(column => self[column])
  end
  
  def authenticate(password)
    if self.password_hash == BCrypt::Engine.hash_secret(password, self.password_salt)
      return true
    else
      return false
    end
  end
  
  def encrypt_password
    if password.present?
      self.password_salt = BCrypt::Engine.generate_salt
      self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
    end
  end
  
  def priority?
      return self.priority.to_i
  end

  def capitalize
    self.name= self.name.capitalize unless !self.name
    self.last_name= self.last_name.capitalize unless !self.last_name
  end
  
  def self.search(search)
    if search
      where('name LIKE ?', "%#{search}%")
    else
      scoped
    end
  end
  
end